﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AssemblyExplorer
{
    public partial class View : UserControl
    {
        private ImageList _imageList;
        public View()
        {
            InitializeComponent();
            
        }

        public IDataProvider DataProvider { get; set; }

        public ImageList ImageList
        {
            get 
            {
                return _imageList;
            }
            set
            {
                this.treeView.ImageList = value;
                this.listView.SmallImageList = value;
                _imageList = value;
            }
        }

        public void Activate()
        {
            treeView.Nodes.Clear();
            var rootItem = this.DataProvider.GetRootDataItem();
            treeView.Nodes.Add(CreateTreeNode(rootItem));
        }

        private static TreeNode CreateTreeNode(DataItem item)
        {
            TreeNode childNode = new TreeNode(item.Text, item.ImageIndex, item.ImageIndex);
            childNode.Tag = item;
            childNode.Nodes.Add("<dumb>");
            return childNode;
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            DataItem dataItem = e.Node.Tag as DataItem;
            textBox.Text = this.DataProvider.GetDescription(dataItem);
            listView.Items.Clear();
            foreach (DataItem item in this.DataProvider.GetListDataItems(dataItem))
            {
                ListViewItem listItem = new ListViewItem(item.Text, item.ImageIndex);
                listItem.Tag = item;
                listView.Items.Add(listItem);
            }
        }

        private void treeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            DataItem dataItem = e.Node.Tag as DataItem;
            e.Node.Nodes.Clear();
            foreach (DataItem item in this.DataProvider.GetChildDataItems(dataItem))
            {
                TreeNode childNode = CreateTreeNode(item);
                e.Node.Nodes.Add(childNode);
            }
        }

        private void listView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(listView.SelectedItems.Count == 1)
            {
                DataItem dataItem = listView.SelectedItems[0].Tag as DataItem;
                textBox.Text = this.DataProvider.GetDescription(dataItem);
            }
        }

    }


}
